package com.zpark.harmonyos_gmd_17.slice;

import com.zpark.harmonyos_gmd_17.ResourceTable;
import com.zpark.harmonyos_gmd_17.utils.HttpRequestUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.TextField;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;

public class LoginAbilitySlice extends AbilitySlice {
    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_login);

        /*
            1、获取用户输入的用户名和密码
            2、获取登录按钮对象
            3、给按钮添加点击事件
            4、发起http请求
            5、接收响应结果/处理响应结果（登录成功，跳转到首页，否则在登录页面提示错误信息）
         */
        TextField uname = (TextField) findComponentById(ResourceTable.Id_login_name_textfield);
        TextField pwd = (TextField) findComponentById(ResourceTable.Id_login_name_textfield);
        // 获取登录按钮对象
        Button btn = (Button) findComponentById(ResourceTable.Id_login_btn);
        // 给按钮添加点击事件
        btn.setClickedListener(component -> {
            // 获取用户输入的用户名和密码
            String username = uname.getText().trim();
            String password = pwd.getText().trim();

            // 定义访问服务器地址
            String url = "http://127.0.0.1:9090/harmony_os/user/login";
            String url1 = "http://httpbin.org/get";

            String param = "{'username': '"+username+"', 'password': '"+password+"'}";

            // 开启异步线程
            TaskDispatcher taskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
            taskDispatcher.asyncDispatch(() -> {
                // 发起http请求
                String result = HttpRequestUtil.sendPostHttpRequestWithData(this, url, param);
                //String result = HttpRequestUtil.sendGetHttpRequest(this, url1);
                System.out.println("*************************************************\n" +
                        result +
                        "\n*************************************************");
            });
        });

    }
}
